
import java.math.BigDecimal;
import java.util.*;

public class Code1161 {

    public static void main(String[] args) {

        TreeNode lleft = new TreeNode();
        lleft.val = 7;
        TreeNode lright = new TreeNode();
        lright.val = -8;

        TreeNode left = new TreeNode();
        left.val = 7;
        left.left = lleft;
        left.right = lright;

        TreeNode right = new TreeNode();
        right.val = 0;

        TreeNode root = new TreeNode();
        root.val = 1;
        root.left = left;
        root.right = right;

        Code1161 code = new Code1161();
        int i = code.maxLevelSum(root);
        System.out.println("---->" + i);
    }

    public int maxLevelSum(TreeNode root) {
        int index = maxLevelSum(root, 0, root.val);

        Set<Map.Entry<Integer, BigDecimal>> entries = sum.entrySet();
        Set<Map.Entry<Integer, BigDecimal>> treeSet = new TreeSet<Map.Entry<Integer, BigDecimal>>(new Comparator<Map.Entry<Integer, BigDecimal>>() {
            public int compare(Map.Entry<Integer, BigDecimal> o1, Map.Entry<Integer, BigDecimal> o2) {
                int valCompare = o2.getValue().compareTo(o1.getValue());
                if (valCompare == 0) {
                    return o2.getValue().compareTo(o1.getValue());
                }
                return valCompare;
            }
        });
        System.out.println(sum);
        treeSet.addAll(entries);
        System.out.println(treeSet);
        Iterator<Map.Entry<Integer, BigDecimal>> iterator = treeSet.iterator();
        if (iterator.hasNext()) {
            Map.Entry<Integer, BigDecimal> next = iterator.next();
            return next.getKey();
        }
        return -1;
    }

    Map<Integer, BigDecimal> sum = new HashMap<Integer, BigDecimal>();

    public int maxLevelSum(TreeNode treeNode, int level, int max) {
        int nextlevel = ++level;
        int left = 0, right = 0;

        boolean b = sum.containsKey(level);
        if (b) {
            BigDecimal bigDecimal = sum.get(level);
            BigDecimal add = bigDecimal.add(new BigDecimal(max));
            sum.put(level, add);
        } else {
            sum.put(level, new BigDecimal(max));
        }
        if (treeNode.left != null) {
            left = maxLevelSum(treeNode.left, nextlevel, treeNode.left.val);
        }
        if (treeNode.right != null) {
            right = maxLevelSum(treeNode.right, nextlevel, treeNode.right.val);
        }
        if ((left + right) > max) {
            return nextlevel;
        } else {
            return level;
        }
    }

}

class TreeNode {
    int val;
    TreeNode left;
    TreeNode right;

    TreeNode() {
    }

    TreeNode(int val) {
        this.val = val;
    }

    TreeNode(int val, TreeNode left, TreeNode right) {
        this.val = val;
        this.left = left;
        this.right = right;
    }
}
